// 傳回'array'當中與指定得 latitude/longitude 最接近的位置
// 假設地表為完美的平面
var findClosestLocatioin = function (lat ,lng ,array) {
var closest;
var closest_dist = Number.MAX_VALUE;
for (var i = 0;i < array.length;i += 1) {
// 將2個點都轉換成為弧度量
var lat_rad = radians(lat);
var lng_rad = radians(lng);
var lat2_rad = radians(array[i].latitude);
var lng2_rad = radians(array[i].longitude);
//使用球面餘弦定理公式
var dist = Math.acos(Math.sin(lat_rad) * Math.sin(lat2_rad) +
Math.cos(lat_rad) * Math.cos(lat2_rad) *
Math.cos(lng2_rad - lng_rad));
if (dist < closest_dist) {
closest = array[i];
closest_dist = dist;
}
}
return closest;
}
迴圈中大多數程式碼在處理格不相關子問題:「計算2個點之間的球面座標值。」有理由將之抽離:
var spherical_distance = function (lat1,lng1,lat2,lng2) {
var lat_rad = radians(lat1);
var lng_rad = radians(lng1);
var lat2_rad = radians(lat2);
var lng2_rad = radians(lng2);
//使用球面餘弦定理公式
var dist = Math.acos(Math.sin(lat_rad) * Math.sin(lat2_rad) +
Math.cos(lat_rad) * Math.cos(lat2_rad) *
Math.cos(lng2_rad - lng_rad));
};
剩下程式碼就成為:
var findClosestLocatioin = function (lat ,lng ,array) {
var closest;
var closest_dist = Number.MAX_VALUE;
for (var i = 0;i < array.length;i += 1) {
var dist = spherical_distance(lat,lng,array[i].latitude,array[i].longitude);
if (dist < closest_dist) {
closest = array[i];
closest_dist = dist;
}
}
return closest;
};